﻿using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace WMSNet.Core.Infrastructure.Api
{
    public class JsonNetFormatter : MediaTypeFormatter
    {
        protected JsonSerializerSettings _jsonSerializerSettings;

        public JsonNetFormatter(JsonSerializerSettings jsonSerializerSettings)
        {
            this._jsonSerializerSettings = jsonSerializerSettings ?? new JsonSerializerSettings();
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            this.MediaTypeMappings.Add((MediaTypeMapping)new QueryStringMapping("format", "json", "application/json"));
        }

        public override bool CanReadType(Type type)
        {
            return true;
        }

        public override bool CanWriteType(Type type)
        {
            return true;
        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            JsonSerializer serializer = JsonSerializer.Create(this._jsonSerializerSettings);
            return Task.Factory.StartNew<object>((Func<object>)(() =>
            {
                using (StreamReader resource_1 = new StreamReader(readStream))
                {
                    using (JsonTextReader resource_0 = new JsonTextReader((TextReader)resource_1))
                        return serializer.Deserialize((JsonReader)resource_0, type);
                }
            }));
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            JsonSerializer serializer = JsonSerializer.Create(this._jsonSerializerSettings);
            return Task.Factory.StartNew((Action)(() =>
            {
                JsonTextWriter local_6 = new JsonTextWriter((TextWriter)new StreamWriter(writeStream));

                local_6.CloseOutput = false;
                using (JsonTextWriter resource_1 = local_6)
                {
                    serializer.Serialize((JsonWriter)resource_1, value);
                    ((JsonWriter)resource_1).Flush();
                }

            }));
        }
    }
}


